package seismosurfer.servlets;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import seismosurfer.data.constants.ParameterNames;
import seismosurfer.util.Notification;
import seismosurfer.util.Util;

import com.bbn.openmap.util.Debug;

/**
 * The base class for most servlets that factorizes
 * common operations.
 *
 */
public class BaseServlet extends HttpServlet implements ParameterNames {
    
    private static final long serialVersionUID = 4833403146165992462L;

    public static final String ERROR = "error";

    public static final String QUAKEID = "quakeid";

    public static final String BGCOLOR = "bgcolor=\"#EFF2F3\"";

    // Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
    
    /**
     * Forwards a request from a servlet to another resource 
     * (servlet, JSP file, or HTML file) on the server.
     * 
     * @param target a String specifying the pathname to the resource
     * @param request a HttpServletRequest object that represents the 
     *         request the client makes of the servlet
     * @param response a HttpServletResponse object that represents the 
     *        response the servlet returns to the client
     * @throws IOException if the target resource throws this exception
     * @throws ServletException if the target resource throws this exception
     */
    protected void forward(String target, HttpServletRequest request,
            HttpServletResponse response) throws IOException, ServletException {

        RequestDispatcher dispatcher = request.getRequestDispatcher(target);
        dispatcher.forward(request, response);
    }
    
    /**
     * Disables caching of the response.
     * 
     * @param response the HttpServletResponse object that represents the response 
     *        the servlet returns to the client
     */
    protected void noCache(HttpServletResponse response) {
        // no cache
        response.setHeader("Cache-Control", "no-cache");
        // response.addHeader("Cache-Control", "max-age=-1");
        response.setHeader("Pragma", "no-cache");
        // response.setHeader("Expires", "-1");
    }
    
    /**
     * Stores the errors in request scope.
     * 
     * @param error the Notification object that contains the errors
     * @param request a HttpServletRequest object that represents the 
     *        request the client makes of the servlet
     * @throws IOException if the target resource throws this exception
     * @throws ServletException if the target resource throws this exception
     */
    protected void setErrors(Notification error, HttpServletRequest request)
            throws IOException, ServletException {

        Map fieldErrors = error.getErrors();
        
        request.setAttribute(ERROR, fieldErrors);

        Debug.output(fieldErrors.toString());
    }
    
    /**
     * Takes a Map of entries and creates an HTML
     * combo box from it.
     * 
     * @param entries the Map of key/values used for the combo box
     * @param selectedCode the selected value
     * @return a text with the HTML snippet
     */
    protected String toComboBox(Map entries, String selectedCode) {
        StringBuffer html = new StringBuffer(200);
        String beginTag = "<option value=\"";
        String endTag = "</option>";
        String selected = "<option selected value=\"";

        Set pairs = entries.entrySet();

        for (Iterator iter = pairs.iterator(); iter.hasNext();) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();

            if (key.equalsIgnoreCase(selectedCode)) {
                html.append(selected);
            } else {
                html.append(beginTag);
            }
            html.append(key + "\">" + value + endTag);
        }
        return html.toString();
    }
    
    /**
     * Creates an HTML link element, given the url and
     * the link label..
     * 
     * @param link the String that contains the url
     * @param text the String that contains the link label
     * @return an HTML link element
     */
    protected String getLink(String link, String text) {
        return "<a href=\"" + link + "\">" + text + "</a>";
    }
    
    /**
     * Gets the {@link #BGCOLOR} color if 
     * the given number is even or an empty
     * String otherwise.
     * 
     * @param i a number that represents a row
     * @return a String that is empty or contains
     *         an HTML color attribute
     */
    protected String getBGColor(int i) {
        String bgcolor;
        if (Util.isEven(i)) {
            bgcolor = "";
        } else {
            bgcolor = BGCOLOR;
        }

        return bgcolor;
    }
    
    /**
     * Converts the given text to an HTML 
     * table cell.
     * 
     * @param content a String that contains the data
     *        to be formatted
     * @return an HTML table cell
     */
    protected String toTD(String content) {
        return "<td> " + content + "</td> ";

    }

}